package com.asiainfo.kbisheet.util

import groovy.util.logging.Slf4j

import com.asiainfo.kbisheet.vo.DBTypeVO
import com.asiainfo.kbisheet.vo.DataSourceVO
import com.asiainfo.kbisheet.vo.SettingVO

/**
 * DBU的工厂类
 * @param databaseSourceVO
 * @return
 */
@Slf4j
class DBUFactory {
	SettingVO settingVO = Setting.getSettingVO()

	/**
	 * 根据数据源(DataSourceVO)创建DBU
	 * @param dataSourceVO
	 * @return
	 */
    DBU createDBU(DataSourceVO dataSourceVO){
		DBTypeVO dbTypeVO = settingVO.dbtypes.find{it.typeName == dataSourceVO.typeName}
		dataSourceVO.setDriverClassName dbTypeVO.getDriverClassName()
		log.debug "创建DBU[" + dbTypeVO.dbuClass + "]..."		
		DBU dbu = (DBU)Class.forName(dbTypeVO.dbuClass).newInstance()		
		dbu.setDataSourceVO dataSourceVO
		dbu.setDbTypeVO dbTypeVO
		dbu
    }
    
	/**
	 * 根据键(key)创建DBU
	 * @param key
	 * @return
	 */
    DBU createDBU(String key){
		log.info "创建DBU[" + key + "]..."
    	DataSourceVO dataSourceVO = settingVO.getDatasources().find{it.key == key}
		if(dataSourceVO == null){
			throw new Exception("数据库KEY:[" + key + "]未发现，请检查配置文件！")
		}
    	createDBU(dataSourceVO)
    }
    
    /**
     * 创建KBiSheet数据的DBU
     * @return
     */
    DBU createKbsBaseDBU(){
		log.info "创建KBS信息库DBU[" + settingVO.kbsbase + "]..."
    	createDBU(settingVO.kbsbase)
    }
}
